/**
 * Created by Eoly on 2017/5/2.
 * Call http://palerock.cn
 */


app.controller('order', function ($http, $scope) {


    $scope.orders = [];
    $scope.selectOrder = null;
    var page = 1;
    var row = 20;
    var isLoading = false;

    $scope.init = function () {
        $(document).on('infinite', '.order-list-content', function () {
            if (isLoading) {
                return;
            }
            $scope.nextOrders();
        });
        $(document).on('refresh', '.pull-to-refresh-content', function (e) {
            $scope.orders = [];
            page = 1;
            isLoading = false;
            $('.infinite-scroll-preloader').show();
            $.attachInfiniteScroll($('.infinite-scroll'));
            $.toast("刷新中...", 500);
            $scope.nextOrders();
            // 加载完毕需要重置
            $.pullToRefreshDone('.pull-to-refresh-content');
        });
        if (!$scope.user) {
            $scope.initUser();
        }
    };

    /**
     * 获取接卸来的工单
     */
    $scope.nextOrders = function () {
        isLoading = true;
        $http({
            method: 'get',
            url: app.netPath + '/order/list',
            params: {
                page: page,
                rows: row
            }
        }).then(function (res) {
            // console.log(res);
            var p = $('.infinite-scroll-preloader');
            var c = $('.content');
            if (!res.data.error) {
                for (var i = 0; i < res.data.pageInfo.list.length; i++) {
                    $scope.orders.push(res.data.pageInfo.list[i]);
                }
                page++;
                isLoading = false;
                if (p.offset().top < c.height()) {
                    $scope.nextOrders();
                }
            } else {
                if (p.offset().top >= c.height()) {
                    $.toast("没有更多工单了", 500);
                }
                // 加载完毕，则注销无限加载事件，以防不必要的加载
                $.detachInfiniteScroll($('.infinite-scroll'));
                // 删除加载提示符
                p.hide();
            }
        }, function (res) {
            // 加载完毕，则注销无限加载事件，以防不必要的加载
            $.detachInfiniteScroll($('.infinite-scroll'));
            // 删除加载提示符
            $('.infinite-scroll-preloader').hide();
        })
    };

    /**
     * 查看工单详情
     * @param order
     */
    $scope.openOrderDetail = function (order) {
        if (!order) {
            return;
        }
        $scope.selectOrder = order;
        // console.log(order);
        $.popup('.popup-detail');
    };

    /**
     * 变更留言
     * @param order
     */
    $scope.changeMsg = function (order) {
        $.prompt('请输入新的留言(50字内)：', '变更留言', function (msg) {
            if (msg == null || msg == '') {
                $.toast("留言不能为空！", 1000);
            }
            $http({
                method: 'post',
                url: app.netPath + "/order/" + order.orderId + '/change-message',
                params: {
                    message: msg
                }
            }).then(function (res) {
                $.toast(res.data.msg, 1200);
                if (!res.data.error) {
                    order.orderCustomerMessage = msg;
                }
            }, function (res) {
                $.alert("网络或设置错误");
            })
        });
    };

    $scope.changeOrderPriority = function (order) {
        var isQuickArr = [{
            name: '正常',
            value: 0
        }, {
            name: '急',
            value: 1
        }, {
            name: '加急',
            value: 2
        }];
        app.filterOptionsAction('改变工单优先级：', isQuickArr, order.orderPriority, function (i) {
            if (i == order.orderPriority) {
                return;
            }
            $.confirm('确认将该工单优先级更改为：[' + isQuickArr[i].name + ']？', function () {
                $http({
                    method: 'post',
                    url: app.netPath + "/order/" + order.orderId + '/change-priority',
                    params: {
                        priority: isQuickArr[i].value
                    }
                }).then(function (res) {
                    $.toast(res.data.msg, 1200);
                    if (!res.data.error) {
                        order.orderPriority = isQuickArr[i].value;
                    }
                }, function (res) {
                    $.alert("网络或设置错误");
                });
            });
        });
    }
});

app.filter("getStatus", function () {
    return function (v) {
        var p = '';
        switch (v.orderPriority) {
            case 0:
                p = '（正常）';
                break;
            case 1:
                p = '（急）';
                break;
            case 2:
                p = '（加急）';
                break;
            default :
                p = '';
                break;
        }
        switch (v.orderStatus) {
            case 0:
                return '未做' + p;
            case 1:
                return '在库' + p;
            case 2:
                return '完工' + p;
            case 3:
                return '已发' + p;
            case 4:
                return '已完成' + p;
            default:
                return '未知状态' + p;
        }
    }
});

app.filter("getLeftMsg", function () {
    return function (v) {
        if (v.orderCustomerMessage != null) {
            return v.orderCustomerMessage
        } else {
            return '暂无';
        }
    }
});

app.filter("getPayStatus", function () {
    return function (v) {
        var money = v.orderPrice;
        switch (v.orderPaymentStatus) {
            case 0:
                return '￥' + money + '（清欠）';
            case -1:
                return '￥' + money + '（未收）';
            default:
                return '￥' + money + '（未知状态）';
        }
    }
});
